package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将数据写入缓存，并设置有效期
     */
    public void set(String key, Object value, Long timeout, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), timeout, timeUnit);
    }

    /**
     * 将数据写入缓存，并设置逻辑过期时间
     */
    public void setWithLogicalExpire(String key, Object value, Long timeout, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        //timeUnit.toSeconds(timeout)是为了确保计时单位是秒
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(timeout)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData) );
    }

    /**
     *
     * 解决缓存穿透
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param timeout
     * @param timeUnit
     * @return
     * @param <R>
     * @param <ID>
     */

    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long timeout, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1.从redis中获取缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.如果缓存中有数据，则直接返回缓存数据
        if (StrUtil.isNotBlank(json)) {

            return JSONUtil.toBean(json, type);
        }
        //判断命中是否空值
        if (json != null) {
            return null;
        }
        //3.如果缓存中没有数据，则查询数据库，并将查询结果缓存到redis中
        R r = dbFallback.apply(id);
        if (r == null) {
            //缓存空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.SECONDS);
            return null;
        }
        this.set(key, r, timeout, timeUnit);
        return r;

    }

    //逻辑过期解决缓存击穿
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id,Class<R> type, Function<ID, R> dbFallback, Long timeout, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1.从redis中获取缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.缓存中有数据是否存在
        if (StrUtil.isBlank(json)) {
            //3.不存在，直接返回null
            return null;
        }
        //4.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1未过期，直接返回店铺对象
            return r;
        }
        //5.2已过期，需要缓存重建
        //6.缓存重建
        // 6.1先尝试获取锁
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        // 6.2判断是否获取锁成功
        if (isLock) {

            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, r1, timeout, timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
            // 6.3成功，开启独立线程，实现缓存重建

        }

        return r;

    }

    //获取锁
    private Boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
